//
//  YCLUserAccountViewModel.swift
//  新浪微博01
//
//  Created by yaochunlin on 16/4/12.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit

class YCLUserAccountViewModel: NSObject {
    
    //设置为单例对象
    static let sharedUserAccountViewModel = YCLUserAccountViewModel()
    
    private override init() {
        
        super.init()
        
        //加载账号
        userAccount = loadUserAccount()
    }
    
    //用户账号属性(为了能够让全局通用)
    var userAccount:YCLUserAccount?
    
    //是否登录
    var isLogin:Bool {
    
        get{
        
            return userAccount != nil
        }
    }
    
    
    
    //获得AccessToken
    func getAccessToken(code: String, callBack:(error: NSError?) ->()){
        
        
        //获得AccessToken
        //网络请求工具类
        let parameters = [
            
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": grant_type,
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        // 1.urlString
        let urlString = accessTokenURLString
        
        YCLNetworkTool.sharedNetworkTool.POST(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) in
            
            YCLPrint("获取access_token成功 \(responseObject)")
            let result = responseObject as? [String: AnyObject]
            
            if let dict = result {
//                2.00rwqD8GkWO_RDb121580bc6eSjI1C
                
                //字典转模型
                self.userAccount = YCLUserAccount.init(dict: dict)
                YCLPrint("用户模型获取成功:\(self.userAccount)")
                
                //保存用户账号信息
//                YCLPrint(path)
                self.savedUserAccount()
 
                callBack(error: nil)
            }
            
            }, failure: { (task, error) in
                
                callBack(error: error)
                YCLPrint("获取access_token失败 \(error)")
        })
        
    }
    
    //获得用户信息
    
    func getUserInfo(callBack: (error: NSError?) -> ()){
        
        
        //判断是否有asscess——token
        guard let access_Token = userAccount?.access_token else{
        
            YCLPrint("没有userAccount或者access_token")
            return
        }
        //判断是否有uid
        guard let uid = userAccount?.uid else {
        
            YCLPrint("没有userAccount或者uid")
            return
        }
        
        //发送网络请求
        let URLString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = [
        
            "access_token" : access_Token,
            "uid": uid
        ]
        
        
        
        YCLNetworkTool.sharedNetworkTool.GET(URLString, parameters: parameters, progress: nil, success: { (task, responseObject) in
            
//                YCLPrint("获取用户信息成功\(responseObject)")
            if let dict = responseObject as? [String : AnyObject]{
                
                self.userAccount?.screen_name = dict["screen_name"] as? String
                self.userAccount?.avatar_large = dict["avatar_large"] as? String

                self.savedUserAccount()
                
                callBack(error: nil)
            }

            
            }) { (task, error) in
                
                YCLPrint("获取用户信息失败\(error)")
                callBack(error: error)
        }
    }
    
    //保存账号信息
    private func savedUserAccount() {
        
        if let userAccount = self.userAccount {
            
          NSKeyedArchiver.archiveRootObject(userAccount, toFile: path!)
        }
    
        //归档

        
    }
    
    //从沙盒中解档
    func loadUserAccount() ->YCLUserAccount? {
    
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path!) as? YCLUserAccount
        
        //可选绑定
        if let account = userAccount where account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
            return account
        }

        return nil
    }
    
}
